﻿using System.Text.RegularExpressions;
using Volo.Abp.DependencyInjection;

namespace AbpCodeGenerater.Core
{
    public class SolutionLoader : ISolutionLoader, ISingletonDependency
    {
        public AbpSolution LoadFrom(string solutionFilePath)
        {
            if (solutionFilePath == null || !solutionFilePath.EndsWith(".sln")) throw new ArgumentNullException("参数solutionFilePath错误");
            var sln = new AbpSolution();

            sln.DirectioryPath = Path.GetDirectoryName(solutionFilePath);
            sln.Name = Path.GetFileNameWithoutExtension(solutionFilePath);

            var soltionContent = File.ReadAllText(solutionFilePath);

            var projectRegex = new Regex(@"Project\(\""\{.*?\}\""\)\s=\s\""(.*?)\"",\s\""(.*?)\"",\s\""\{.*?\}\""");
            var matchs = projectRegex.Matches(soltionContent);

            foreach (Match match in matchs)
            {
                var name = match.Result("$1");
                if (name == null) continue;
                if (!name.EndsWith(".Domain") && !name.EndsWith(".HttpApi.Host")) continue;

                var csprojPath = match.Result("$2");
                if (csprojPath == null) continue;

                var abpProject = new AbpProject();
                abpProject.Name = name;
                abpProject.Path = Path.GetDirectoryName(csprojPath);
                abpProject.FullPath = Path.Combine(sln.DirectioryPath ?? string.Empty, abpProject.Path ?? string.Empty);
                abpProject.AbpSolution = sln;

                if (name.EndsWith(".HttpApi.Host"))
                {
                    sln.StartUpProject = abpProject;
                    continue;
                }

                sln.DomainProjects.Add(abpProject);
            }

            return sln;
        }
    }
}
